// Package api
// @Author: zhangdi
// @File: sys_common
// @Version: 1.0.0
// @Date: 2023/9/5 16:50
package sysctrl

import (
	"github.com/gin-gonic/gin"
	"io"
	"os"
	"path/filepath"
	"server/application/constant/syscnt"
	"server/application/db/system/dbsvc"
	"server/application/dto"
	"server/pkg/configs"
	"server/pkg/ginp"
	"server/pkg/utils"
	"server/setting"
	"strings"
	"time"
)

// SysCommonUpload 文件上传接口
func SysCommonUpload(c *ginp.ContextPro) {

	// 获取上传的文件
	file, err := c.FormFile("file")
	if err != nil {
		c.ErrJson(err.Error())
		return
	}

	// 构建目标文件的路径
	currentTime := time.Now()
	dateFolder := currentTime.Format("2006-01-02")
	guid := utils.GetGuidStr()
	timeFilename := currentTime.Format("15-04-05") + "_" + guid + filepath.Ext(file.Filename)

	//图片和文件存放的路径不一致
	uploadDir := "./static/upload_images/" + dateFolder + "/"
	if !isImageFile(filepath.Ext(file.Filename)) {
		uploadDir = "./static/upload_files/" + dateFolder + "/"
	}
	dstPath := uploadDir + timeFilename
	err = os.MkdirAll(uploadDir, os.ModePerm)
	if err != nil {
		c.ErrJson(err.Error())
		return
	}

	dst, err := os.Create(dstPath)
	if err != nil {
		c.ErrJson(err.Error())
		return
	}
	defer dst.Close()
	// 将上传的文件写入目标文件
	src, err := file.Open()
	if err != nil {
		c.ErrJson(err.Error())
		return
	}
	defer src.Close()

	_, err = io.Copy(dst, src)
	if err != nil {
		c.ErrJson(err.Error())
		return
	}

	c.OkJsonData(strings.ReplaceAll(dstPath, "./", "/"))

}

func isImageFile(filename string) bool {
	imageExtensions := []string{".jpg", ".jpeg", ".gif", ".png", ".bmp"} // 可扩展其他图片格式

	extension := strings.ToLower(filename[strings.LastIndex(filename, "."):])
	for _, ext := range imageExtensions {
		if ext == extension {
			return true
		}
	}

	return false
}

// SysCommonSaveConfigs 保存配置
func SysCommonSaveConfigs(ctx *ginp.ContextPro) {
	var params *dto.ReqSysCommonSaveConfigs
	if err := ctx.ShouldBindJSON(&params); err != nil {
		ctx.ErrJson("请求参数有误" + err.Error())
		return
	}
	for k, v := range params.Data {
		configs.GetConf().Set(k, v)
	}
	dbsvc.SysCommonDeleteTempDir()
	ctx.OkJson()
}

// SysCommonGetConfigs 获取配置列表，返回map
func SysCommonGetConfigs(ctx *ginp.ContextPro) {
	var params *dto.ReqSysCommonGetConfigs
	if err := ctx.ShouldBindJSON(&params); err != nil {
		ctx.ErrJson("请求参数有误" + err.Error())
		return
	}

	res := make(map[string]any)
	for _, key := range params.Keys {
		res[key] = configs.GetConf().Get(key)
	}

	ctx.OkJsonData(res)
}

// SysCommonGetSiteInfo 获取站点的配置信息
func SysCommonGetSiteInfo(ctx *ginp.ContextPro) {
	ctx.OkJsonData(gin.H{
		syscnt.SysKeyBeiAn:    setting.Beian,    //备案号
		syscnt.SysKeyWebTitle: setting.WebTitle, //首页标题
	})

}
